/**
 * 
 */
package br.com.ufc.apsoo.hotelar.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.ufc.apsoo.hotelar.dao.ClienteDao;
import br.com.ufc.apsoo.hotelar.model.Cliente;
import br.com.ufc.apsoo.hotelar.utils.HibernateUtil;

/**
 * @author Virginia
 * 
 */
public class ClienteDaoImpl implements ClienteDao {

	@Override
	public void save(Cliente cliente) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.save(cliente);
		t.commit();
		session.close();
	}

	@Override
	public void remove(Cliente cliente) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.delete(cliente);
		t.commit();
		session.close();
	}

	@Override
	public void update(Cliente cliente) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.update(cliente);
		t.commit();
		session.close();
	}

	@Override
	public Cliente getClienteById(int id) {
		Session session = HibernateUtil.getSession();
		try {
			return (Cliente) session.get(Cliente.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> list() {
		Session session = HibernateUtil.getSession();
		try {
			return session.createCriteria(Cliente.class).list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@Override
	public Cliente getClienteByCpf(String cpf) {
		Session session = HibernateUtil.getSession();
		String query = "from Cliente where cpf = :cpf";
		try {
			return (Cliente) session.createQuery(query).setString("cpf", cpf)
					.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> getClienteByNome(String nome) {
		Session session = HibernateUtil.getSession();
		String query = "from Cliente where nome like :nome";
		try {
			System.out.println(nome);
			return session.createQuery(query).setString("nome", "%" + nome + "%").list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> getClienteByNomeAndHospedado(String nome) {
		Session session = HibernateUtil.getSession();
		String query = "select h.cliente from Hospedagem h left join h.cliente where h.cliente.nome like :nome and h.status = true";
		try {
			System.out.println(nome);
			return session.createQuery(query).setString("nome", "%" + nome + "%").list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

}
